package com.zyht.bank.wechat.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.github.pagehelper.PageHelper;
import com.wx.model.BussinessException;
import com.wx.model.dictionary.Constant;
import com.zyht.bank.entity.AxdCertificateImge;
import com.zyht.bank.entity.AxdCustInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.service.AxdCertificateImgeService;
import com.zyht.bank.service.AxdCertificateInfoService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.bank.wechat.http.AjaxMain;
import com.zyht.bank.wechat.http.EnumCode;
import com.zyht.bank.wechat.http.HttpCommon;
import com.zyht.bank.wechat.intercepter.Binding;
import com.zyht.bank.wechat.utils.ImageUtil;
import com.zyht.bank.wechat.utils.UploadImageRes;
import com.zyht.bank.wechat.vo.Image;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.wechat.framework.constant.ConfigConstants;

/**
 * 凭证上传
 * 
 * @author qjl
 * @data 2017年7月8日
 */
@Controller
@RequestMapping("anon/photo")
public class PhotoController implements HttpCommon {
	private Logger logger = LoggerFactory.getLogger(PhotoController.class);

	@Resource
	private AxdOrgInfoService axdOrgInfoService;

	@Resource
	private AxdCertificateInfoService axdCertificateInfoService;

	@Resource
	private AxdCertificateImgeService axdCertificateImgeService;

	@RequestMapping("/uploadImage")
	@Binding
	public void uploadImage(HttpServletRequest request, HttpServletResponse response) {
		
		// 获取用户信息
		AxdCustInfo custInfo = (AxdCustInfo) request.getSession()
				.getAttribute(Constant.CURRENT_USER_BINDINFO_FROM_EVENT_VIEW);
		// 保存图片路径
		AxdCertificateImge axdCertificateImge = new AxdCertificateImge();
		UploadImageRes res = exeAjax(UploadImageRes.class, new AjaxMain<UploadImageRes>() {
			@Override
			public void exe(UploadImageRes res) throws BussinessException {
				// 获取解析器
				CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
				resolver.setResolveLazily(true);
				// 判断是否是文件
				if (resolver.isMultipart(request)) {
					// 进行转换
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) (request);
					// 获取所有文件名称
					Iterator<String> it = multiRequest.getFileNames();
					// 生成图片的名字 UUid
					UUID uuid = UUID.randomUUID();
					String uuidStr = uuid.toString();
					String fileName = uuidStr.replace("-", "");
					int index = 0;
					// 获取用户信息

					String pricePath = getPath(custInfo);
					// 获取配置文件中的路径
					String realPath = PropertiesUtils.getConfig(ConfigConstants.PHONE_FILE_UPLOAD_DIR);
					pricePath="/cust" + pricePath;
					// 文件上传目录
					String rootPath = realPath +pricePath;
					logger.debug("开始上传图片-------");
					if (it.hasNext()) {
						MultipartFile multipartFile = multiRequest.getFile(it.next());
						if (!multipartFile.isEmpty()) {
							try {
								// 这里要进行判断，即使是空值，没有上传内容，file都是有值（空值）的，而文件流大小要大于0才是有上传的东西
								if (multipartFile.getSize() > 0) {
									ByteArrayInputStream in = new ByteArrayInputStream(multipartFile.getBytes());
									BufferedImage bimage = ImageIO.read(in);
									if (bimage != null) { // 如果image不为空，则说明file文件是图片
										// 后缀名
										String tempName = multipartFile.getOriginalFilename();
										String fileType = tempName.substring(tempName.lastIndexOf(".") + 1)
												.toLowerCase();
										// 原图地址
										// 压缩图
										String compress = realPath + "/cust/" + custInfo.getCustIdNum() + "/compress/"
												+ new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
										// 缩略图
										// String thumbnail = realPath +
										// custInfo.getCustIdNum() +
										// "/thumbnail/";
										File file = new File(rootPath);
										if (!file.exists()) {
											file.mkdirs();
										}
										File comprefile = new File(compress);
										if (!comprefile.exists()) {
											comprefile.mkdirs();
										}
										fileName += index;
										multipartFile.transferTo(new File(rootPath + fileName + "." + fileType));
										index++;
										// 读取原图
										File localFile = new File(rootPath, fileName + "." + fileType);
										axdCertificateImge.setImgUrl(pricePath + fileName + "." + fileType);
										// 压缩图
										String compressPath = compress + fileName + "." + fileType;
										ImageUtil.zoomImageScale(localFile, compressPath, 200);
										// 缩略图
										// String thumbnailPath = rootPath +
										// "thumbnail/" + fileName +
										// "_thumbnail."
										// + fileType;
										// ImageUtil.zoomImageScale(compressPath,
										// thumbnailPath, 200);
										Image info = new Image();
										info.setName(multipartFile.getOriginalFilename());
										info.setPath(pricePath + fileName + "." + fileType);
										info.setHeight(bimage.getHeight());
										info.setWidth(bimage.getWidth());
										info.setUrl(PropertiesUtils.getConfig(ConfigConstants.PHONE_FILE_UPLOAD_URL));
										res.setImage(info);
										res.setCode(EnumCode.success);
										setSuccess(res, "上传成功");

										return;
									}
								} else {
									res.setCode(EnumCode.error);
									setError(res, "图片不能为空");
									return;
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}

				setError(res, "未知文件");
				return;
			}
		});
		logger.info("图片上传成功！");
		writePlain(response, cvJson(res));
		return;
	}

	private String getPath(AxdCustInfo custInfo) {
		// 获取用户信息
		String custIdNum = custInfo.getCustIdNum();
		// 获取机构
		AxdOrgInfoExample example = new AxdOrgInfoExample();
		example.createCriteria().andOrgCodeEqualTo(custInfo.getLoanOrgCode());
		PageHelper.startPage(1, 1);
		SimpleDateFormat sfd = new SimpleDateFormat("yyyyMMdd");
		String format = sfd.format(new Date());
		String path = "/" + custIdNum + "/normal/" + format + "/";
		return path;
	}
}
